<div class="title">Ebay Listing Form - Edit a listing</div>
<div id="category" class="section"><div onclick="listingForm.categoryChooser.toggle();">Choose Category</div></div>
<div id="uploadPhotos" class="section" style="">
    <div id="imageBox">
    </div>
    <div id="imageForm">
        <form id="uploadImages" method="post" enctype="multipart/form-data" target="upload_iframe" action="/uploadimages">
            <div class="field"><?= $this->formFile('image[0]'); ?><?= $this->formFile('image[1]'); ?></div>
            <div class="field"><?= $this->formFile('image[2]'); ?><?= $this->formFile('image[3]'); ?><input type="submit" id= "uploadImages"  value="Upload" /></div>
        </form>
    </div>
</div>
<?php
$ebay = new Ebay_Client();

$features = $ebay->getCatgoryFeatures($this->item['cid'], array('ListingDurations', 'ItemSpecificsEnabled'));
$days;
foreach($features->FeatureDefinitions->ListingDurations->ListingDuration as $duration)
{
    if($duration->attributes()->durationSetID == 1)
    {
        $days = $duration->Duration;
    }
}
$options = array();
//Extract the duration from each string
foreach($days as $str)
{
    $time = substr($str, 5);
    $options[] = $time;
}

$currency = new Zend_Currency();
$cSymbol = $currency->getSymbol(); //Load up the currency symbol for the locale
$this->item['details'] = unserialize($this->item['details']);
$paymentOptions = explode(',',$this->item['details']->paymentOptions);

$paypalAddress = $this->user->paypal;
if(isset($this->item['details']->paypalAddress))
{
	$paypalAddress = $this->item['details']->paypalAddress;
}
?>
<div id="listingForm" class="section">
    <div id="listing" style="">
        <form id="listingform">
            <div>
                <?= $this->formLabel('title', 'Title:' ) ?>
                <?= $this->formText('title', isset($this->item) ? $this->item['title'] : '') ?>
            </div>
            <div>
                <?= $this->formLabel('description', 'Description:') ?>
                <?= $this->formTextarea('description', isset($this->item) ? $this->item['description'] : '') ?>
            </div>
            <div>
                <?= $this->formLabel('startPrice', 'Starting price:' . $cSymbol) ?>
                <?= $this->formText('startPrice', isset($this->item) ? $this->price($this->item['startPrice']) : '') ?>
            </div>
            <div>
                <?= $this->formLabel('duration', 'Duration:') ?>
                <?= $this->formSelect('duration', $this->item['duration'], null, $options) ?>
                <?php // $this->formText('duration', isset($this->item) ? $this->item['duration'] : '') ?>
            </div>
            <div>
                <?= $this->formLabel('delivery', 'Delivery to UK:' . $cSymbol) ?>
                <?= $this->formText('delivery', isset($this->item) ? $this->price($this->item['delivery']) : '') ?>
            </div>
			<div>
				<?= $this->myCheckbox('payment', 'PayPal', $paymentOptions, 'Paypal: ', 'payment-paypal') ?> 
				<span id="span-paypalAddress"><?= $this->formLabel('paypalAddress', 'Paypal Email: ') ?> <?= $this->formText('paypalAddress', $paypalAddress) ?></span><br />
				<?= $this->myCheckbox('payment', 'PersonalCheck', $paymentOptions, 'Cheque: ') ?><br />
				<?= $this->myCheckbox('payment', 'PostalTransfer', $paymentOptions, 'Postal order: ') ?><br />
				<?= $this->myCheckbox('payment', 'Other', $paymentOptions, 'Other payment: ') ?><br />
            </div>
        </form>
    </div>
</div>
<div id="confirmation" class="section" style="display:none;">
<ul class="fees">
</ul>
<span class="submit" onclick="listingForm.showForm()">Cancel</span>
<span class="submit" onclick="app.submitListings(true);"><?php echo htmlspecialchars('Confirm & Submit'); ?></span>
</div>
<div id="editor-tasks" class="section">
<span class="submit" onclick="listingForm.send({job: 'save'})">Save</span>
<span class="submit" onclick="listingForm.send({job: 'submit'})"><?php echo htmlspecialchars('Save & Submit'); ?></span>
</div>
<?php

    $Images = new Images();
    $images = $Images->fetchAll($Images->select()->where('id = ?', $this->item['id']))->toArray();

?>
<script type="text/javascript">

    window.listingForm = new MyForm('listingform', {
    init: function()
    {
        this.listingId = <?php echo isset($this->item) ? $this->item['id'] : ''; ?>;
        this.categoryChooser = new Ebay.CategoryChooser({
            level: <?php echo $this->category['level'] + 1; ?>,
            cid: <?php echo $this->category['cid']; ?>,
            pid: <?php echo $this->category['cid']; ?>});
			
        $('category').insert(this.categoryChooser.hide());
		
        this.uploadForm = new Ebay.UploadImageForm(<?= Zend_Json::encode($images) ?>);
		if(!$('payment-paypal').checked)
		{
			$('span-paypalAddress').hide();
		}
		$('payment-paypal').observe('click', function(){
			$('span-paypalAddress').toggle();
		});
		
        document.observe('category:notpicked', function()
        {
        $('listingform').disable().fade({to: 0.7});
        });

        document.observe('category:chosen', function(){
            this.categoryChooser.hide();
            $('listingform').enable().appear({from: 0.7});
			
			var cid = this.categoryChooser.cid;
			if(this.prevCid != cid)
			{
				$('duration').insert('<span class="loading">Loading...</span>', {position: 'After'});
				new Ajax.Request('/ajax/getcategorydetails/' + cid, {onSuccess: function(t)
				{
					var json = t.responseJSON;
					if(json && json.status)
					{
						this.duration = $('duration').selectedIndex.value;
						$('duration').update();
						json.details.duration.each(function(d)
						{
							var isSelected = (d == this.duration) ? true : false;
							$('duration').insert(new Element('option', {value : d, selected: isSelected}).insert(d + ' Days'));
						}.bind(this));
						
						$('categorySpecifics').update();
						json.details.specifics.each(function(s)
						{
							
							$('categorySpecifics').insert(new Element('label', {for: 'specific-' + s.key}).insert(s.key));
							if(s.values)
							{
								$('categorySpecifics').insert(new Element('select', {id: 'specific-' + s.key}));
								s.values.each(function(s){
									$('specific-' + this.key).insert(new Element('option', {value: s}).update(s));
								}.bind(s));
							}
							else
							{
								$('categorySpecifics').insert(new Element('input', {type: 'text', id: 'specific-' + s.key}));
							}
						});
						$$('span.loading').remove();
					}
				}.bind(this)
				});
			}
			this.prevCid = cid;
			
        }.bind(this));
		
        document.observe('form:success', function()
        {
			
        });
		
		document.stopObserving('dialog:close');
        document.observe('dialog:close', this.closeDialog.bind(this));
    },
	closeDialog: function()
	{
		if(confirm('Are you sure about closing the window, before saving?'))
		{
			app.dialog.close();
			this.destroy();
		}
	},
	destroy: function()
	{
		document.stopObserving('category:notpicked').stopObserving('category:chosen').stopObserving('dialog:close');
	}, 
	showForm: function()
	{
		app.dialog.el.select('div.section').invoke('show');
		$('confirmation').hide();
	},
    success: function(t)
    {	
		var json = t.responseJSON;
		if(!json.status)
		{
			return;
		}
		
		// Automatically sync the listing if available
        if(json.listing)
        { 
            var listing = json.listing;
			app.updateListing(listing);
            app.table.updateRow(listing.id);            
        }
		
		if(this.job == 'save')
		{
			app.dialog.close();
		}
        else if(this.job == 'submit' && json.request == 'validate')
        {
            var fees = json.fees;
			app.dialog.el.select('div.section').invoke('hide');
			$('confirmation').show().down('ul.fees').update();
			fees.each(function(s)
			{
				var txt = s[0] + ' - <b>' + s[1] + '</b>';
				$('confirmation').down('ul.fees').insert( new Element('li').insert(txt) );				
			});
			app.idList = [this.listingId];
        }
		else if(this.job == 'submit' && json.request == 'submitted')
		{
			var listing = json.listing;
            Object.extend(app.findListing(listing.id), listing);
            app.table.updateRow(app.findListing(listing.id).rowId);
            app.dialog.close();

		}
    },
    submit: function(params){
        this.data = this.el.serialize(true);
        this.data.id = this.listingId;
		
        this.job = params.job;
		
        this.data.cid = this.categoryChooser.cid;
        new Ajax.Request('/ajax/edit/' + params.job, {parameters: {json : Object.toJSON(this.data)}, 
			onSuccess: this.process.bind(this)});
    }
    });
</script>